<?php

class Order extends Eloquent{
	
	protected $guarded = array('id');
	
	public function products(){
		return $this->hasMany("OrderProduct");
// 		return 
		//return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
	}

	public function card(){
		return $this->hasOne("OrderCard");
	}
	
	public function address(){
		
		return $this->belongsTo("UserAddress","user_address_id");
	}
	
	public function user(){
		return $this->belongsTo("User","user_id");
	}
	
	public function recycle($data){
		$order = $this;
		DB::transaction(function() use ($data,$order){
			$oldStatus = $order->status;
			
			$order->update($data);
			if ($oldStatus == $data['status']){
				return;
			}
			$products = $order->products;
			$products->each(function($product){
				//规格
				$quantity = $product->quantity;
				if (!empty($product->size_id)){
					ProductSizes::where('id','=',$product->size_id)->increment('quantity',$quantity);
				} else if (!empty($product->color_id)){
					ProductColors::where('id','=',$product->color_id)->increment('quantity',$quantity);
				}
		
				Products::where('id','=',$product->product_id)->increment('quantity',$quantity);
			});
			//$affectedRows = Order::where('id', '=', $order->id)->where('status')->update(array('status' => 4));
			//DB::table('users')->update(array('votes' => 1));
			//DB::table('posts')->delete();
		});
	}
}
